import React from 'react';
import Mynavbar from '@/components/Mynavbar';
import { useEffect, useState, useRef } from 'react';
import { useSelector } from 'react-redux';
import { getCarListApi } from '@/api/detail'
import { useCallback, useMemo } from 'react';
import {
    Image,
    List,
    Stepper,
    Ellipsis,
    Empty,
    Button,
    Space,
    Checkbox,
    Dialog,
    SwipeAction
} from 'antd-mobile';
import { useHistory } from 'react-router-dom'

import {
    updateCheckedAllApi,
    updateCheckedOneApi,
    updateOneNumApi,
    deleteOneApi
} from '@/api/cart'
// import { Action, SwipeActionRef } from 'antd-mobile/es/components/swipe-action'
const Cart = () => {
    // 获取仓库数据
    const userId = useSelector(state => state.userId);
    // console.log('userId', userId);
    const [carNum, setCarNum] = useState(0);
    const [cartlist, setCartList] = useState([]);
    const his = useHistory();

    // 定义全选变量
    const [checkedAll, setCheckedAllFn] = useState(false)
    const getcartlist = useCallback(() => {
        getCarListApi({ userid: userId }).then(res => {
            // console.log(res);
            if (res.data.code == '10020') {
                setCarNum(0);
                setCartList([]);
                setCheckedAllFn(false);
            } else {
                setCartList(res.data.data)
                setCarNum(res.data?.data?.length)
                // console.log(res.data.data.every((item) => item.flag));
                setCheckedAllFn(res.data.data.every((item) => item.flag))
            }
        })
    }, [])
    useEffect(() => {
        getcartlist();
    }, [])

    // const ref = useRef < SwipeActionRef > (null)
    // 使用计算属性 计算商品总价
    // 语法:const 变量=  useMemo(()=>{return 值1},[依赖的变量]) 值1就是变量的值
    const arr = [1, 2, 3, 4, 5];
    // const total = arr.reduce((sum, item) => { return sum += item }, 0)
    //console.log('total', total);
    const totalPrice = useMemo(() => {
        return cartlist.reduce((sum, item) => { return item.flag ? sum += item.originprice * item.num : sum }, 0)
    }, [cartlist])
    return (
        <div>
            {/* 头部导航 */}
            <Mynavbar isshowright={false}>{`购物车(${carNum})`}</Mynavbar>
            {/* 购物车列表 */}
            {
                cartlist.length == 0 ? <Empty
                    style={{ padding: '64px 0' }}
                    imageStyle={{ width: 128 }}
                    description={
                        <div>
                            <p style={{
                                textAlign: 'center',
                                marginBottom: '10px'
                            }}>{'暂无数据'}</p>
                            <Button color='danger' size='small' onClick={() => {
                                // 跳转到首页
                                his.push('/home')
                            }}>立即购物</Button>
                        </div>
                    }
                /> :
                    <List>
                        {cartlist.map(item => (
                            <SwipeAction
                                key={item.cartid}
                                rightActions={[
                                    {
                                        key: 'delete',
                                        text: '删除',
                                        color: 'danger',
                                        onClick: async () => {
                                            await Dialog.confirm({
                                                content: '确定要删除吗？',
                                            })

                                            //console.log('123')
                                            // ref.current?.close()
                                            deleteOneApi({ cartid: item.cartid }).then(res => {
                                                console.log(res)
                                                getcartlist()
                                            })
                                        },
                                    }
                                ]}
                            >
                                <List.Item
                                    key={item.cartid}
                                    prefix={
                                        <Space align='center'>
                                            <div onClick={e => e.stopPropagation()}>
                                                <Checkbox checked={item.flag} onChange={(boolean) => {
                                                    console.log(boolean)
                                                    updateCheckedOneApi({
                                                        cartid: item.cartid,
                                                        flag: boolean
                                                    }).then(res => {
                                                        console.log(res)
                                                        getcartlist()
                                                    })
                                                }} />
                                            </div>
                                            <Image
                                                src={item.img1}
                                                fit='cover'
                                                width={60}
                                                height={60}
                                            />
                                        </Space>

                                    }
                                    description={
                                        <div style={{
                                            display: 'flex',
                                            justifyContent: 'space-between',
                                            alignItems: 'center'
                                        }}>
                                            <p>{item.originprice}</p>
                                            {/* 步进器 */}
                                            <Stepper
                                                value={item.num}
                                                onChange={value => {
                                                    console.log(value)
                                                    if (value == 0) {
                                                        deleteOneApi({ cartid: item.cartid }).then(res => {
                                                            console.log(res)
                                                            getcartlist()
                                                        })
                                                    } else {
                                                        updateOneNumApi({
                                                            cartid: item.cartid,
                                                            num: value
                                                        }).then(res => {
                                                            console.log(res)
                                                            getcartlist()
                                                        })
                                                    }

                                                }}
                                            />
                                        </div>
                                    }
                                >
                                    <div >
                                        <Ellipsis
                                            direction='end'
                                            rows={2}
                                            style={{
                                                fontSize: '14px'
                                            }}
                                            content={item.proname}
                                        />
                                    </div>
                                </List.Item>
                            </SwipeAction>
                        ))}
                    </List>
            }
            {/* 底部tabbar 组件 */}
            <div style={{
                position: 'fixed',
                left: 0,
                bottom: 0,
                display: 'flex',
                justifyContent: 'space-around',
                width: '100%',
                alignItems: 'center'
            }}>
                <Checkbox checked={checkedAll} onChange={(bool) => {
                    //调用接口
                    updateCheckedAllApi({ type: bool, userid: userId }).then(res => {
                        // console.log(res)
                        getcartlist()
                    })
                }}>全选</Checkbox>
                <p>总价:{totalPrice.toFixed(2)}元</p>
                <Button color='danger'>合计</Button>
            </div>

        </div>
    );
}

export default Cart;
